use std::env;
use std::fs;
use std::vec;
use std::process;
use std::error::Error;

//配置
pub struct Config{
     query:String,
     filename: String,
}
impl Config{
    pub fn new(mut args: std::env::Args) -> Result<Config, & 'static str> {
        if args.len() < 3{
            return Err("参数错误");
        }
        args.next(); //跳过第一个参数(程序名称)

        let query = match args.next(){
            Some(arg) => arg,
            None => return Err("获取参数失败"),
        }; //搜索的内容
        let filename =match args.next(){
            Some(arg) => arg,
            None => return Err("获取参数失败"),
        }; //搜索的文件
        Ok(Config{
            query,
            filename
        })
    }
}
//读取文件指定内容
pub fn read_file_demo(){

    //获取命令行参数
    //let args: Vec<String> = env::args().collect();
    let config = Config::new(env::args()).unwrap_or_else(|err|{
        eprintln!("{}", err); //标准错误输出
        process::exit(1);
    });
    if let Err(e) = run(config){
        println!("{}", e);
        process::exit(1);
    }
}

pub fn run(config: Config) -> Result<(),Box<dyn Error>>{
    let content = fs::read_to_string(config.filename)?;
    for line in search(&config.query, &content){
        println!("{}", line)
    }
    Ok(())
}

pub fn search<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
    /*let mut results = Vec::new();
    for line in content.lines() {
        //不区分大小
        if line.to_lowercase().contains(&query.to_lowercase()) {
            results.push(line);
        }
    }
    return results;
    */
    //使用迭代器
    content.lines()
        .filter(|line| line.contains(query))
        .collect()

}

#[cfg(test)]
mod tests{
    #[test]
    fn one_result(){
        //assert_eq!(vec![])
    }
}